
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" lang="en">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Migrations &#8212; Django 2.2.12.dev20200304094918 documentation</title>
    <link rel="stylesheet" href="../_static/default.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/language_data.js"></script>
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="next" title="Managing files" href="files.html" />
    <link rel="prev" title="Using mixins with class-based views" href="class-based-views/mixins.html" />



 
<script type="text/javascript" src="../templatebuiltins.js"></script>
<script type="text/javascript">
(function($) {
    if (!django_template_builtins) {
       // templatebuiltins.js missing, do nothing.
       return;
    }
    $(document).ready(function() {
        // Hyperlink Django template tags and filters
        var base = "../ref/templates/builtins.html";
        if (base == "#") {
            // Special case for builtins.html itself
            base = "";
        }
        // Tags are keywords, class '.k'
        $("div.highlight\\-html\\+django span.k").each(function(i, elem) {
             var tagname = $(elem).text();
             if ($.inArray(tagname, django_template_builtins.ttags) != -1) {
                 var fragment = tagname.replace(/_/, '-');
                 $(elem).html("<a href='" + base + "#" + fragment + "'>" + tagname + "</a>");
             }
        });
        // Filters are functions, class '.nf'
        $("div.highlight\\-html\\+django span.nf").each(function(i, elem) {
             var filtername = $(elem).text();
             if ($.inArray(filtername, django_template_builtins.tfilters) != -1) {
                 var fragment = filtername.replace(/_/, '-');
                 $(elem).html("<a href='" + base + "#" + fragment + "'>" + filtername + "</a>");
             }
        });
    });
})(jQuery);</script>

  </head><body>

    <div class="document">
  <div id="custom-doc" class="yui-t6">
    <div id="hd">
      <h1><a href="../index.html">Django 2.2.12.dev20200304094918 documentation</a></h1>
      <div id="global-nav">
        <a title="Home page" href="../index.html">Home</a>  |
        <a title="Table of contents" href="../contents.html">Table of contents</a>  |
        <a title="Global index" href="../genindex.html">Index</a>  |
        <a title="Module index" href="../py-modindex.html">Modules</a>
      </div>
      <div class="nav">
    &laquo; <a href="class-based-views/mixins.html" title="Using mixins with class-based views">previous</a>
     |
    <a href="index.html" title="Using Django" accesskey="U">up</a>
   |
    <a href="files.html" title="Managing files">next</a> &raquo;</div>
    </div>

    <div id="bd">
      <div id="yui-main">
        <div class="yui-b">
          <div class="yui-g" id="topics-migrations">
            
  <div class="section" id="s-module-django.db.migrations">
<span id="s-migrations"></span><span id="module-django.db.migrations"></span><span id="migrations"></span><h1>Migrations<a class="headerlink" href="#module-django.db.migrations" title="Permalink to this headline">¶</a></h1>
<p>Migrations are Django’s way of propagating changes you make to your models
(adding a field, deleting a model, etc.) into your database schema. They’re
designed to be mostly automatic, but you’ll need to know when to make
migrations, when to run them, and the common problems you might run into.</p>
<div class="section" id="s-the-commands">
<span id="the-commands"></span><h2>The Commands<a class="headerlink" href="#the-commands" title="Permalink to this headline">¶</a></h2>
<p>There are several commands which you will use to interact with migrations
and Django’s handling of database schema:</p>
<ul class="simple">
<li><a class="reference internal" href="../ref/django-admin.html#django-admin-migrate"><code class="xref std std-djadmin docutils literal notranslate"><span class="pre">migrate</span></code></a>, which is responsible for applying and unapplying
migrations.</li>
<li><a class="reference internal" href="../ref/django-admin.html#django-admin-makemigrations"><code class="xref std std-djadmin docutils literal notranslate"><span class="pre">makemigrations</span></code></a>, which is responsible for creating new migrations
based on the changes you have made to your models.</li>
<li><a class="reference internal" href="../ref/django-admin.html#django-admin-sqlmigrate"><code class="xref std std-djadmin docutils literal notranslate"><span class="pre">sqlmigrate</span></code></a>, which displays the SQL statements for a migration.</li>
<li><a class="reference internal" href="../ref/django-admin.html#django-admin-showmigrations"><code class="xref std std-djadmin docutils literal notranslate"><span class="pre">showmigrations</span></code></a>, which lists a project’s migrations and their
status.</li>
</ul>
<p>You should think of migrations as a version control system for your database
schema. <code class="docutils literal notranslate"><span class="pre">makemigrations</span></code> is responsible for packaging up your model changes
into individual migration files - analogous to commits - and <code class="docutils literal notranslate"><span class="pre">migrate</span></code> is
responsible for applying those to your database.</p>
<p>The migration files for each app live in a “migrations” directory inside
of that app, and are designed to be committed to, and distributed as part
of, its codebase. You should be making them once on your development machine
and then running the same migrations on your colleagues’ machines, your
staging machines, and eventually your production machines.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">It is possible to override the name of the package which contains the
migrations on a per-app basis by modifying the <a class="reference internal" href="../ref/settings.html#std:setting-MIGRATION_MODULES"><code class="xref std std-setting docutils literal notranslate"><span class="pre">MIGRATION_MODULES</span></code></a>
setting.</p>
</div>
<p>Migrations will run the same way on the same dataset and produce consistent
results, meaning that what you see in development and staging is, under the
same circumstances, exactly what will happen in production.</p>
<p>Django will make migrations for any change to your models or fields - even
options that don’t affect the database - as the only way it can reconstruct
a field correctly is to have all the changes in the history, and you might
need those options in some data migrations later on (for example, if you’ve
set custom validators).</p>
</div>
<div class="section" id="s-backend-support">
<span id="backend-support"></span><h2>Backend Support<a class="headerlink" href="#backend-support" title="Permalink to this headline">¶</a></h2>
<p>Migrations are supported on all backends that Django ships with, as well
as any third-party backends if they have programmed in support for schema
alteration (done via the <a class="reference internal" href="../ref/schema-editor.html"><span class="doc">SchemaEditor</span></a> class).</p>
<p>However, some databases are more capable than others when it comes to
schema migrations; some of the caveats are covered below.</p>
<div class="section" id="s-postgresql">
<span id="postgresql"></span><h3>PostgreSQL<a class="headerlink" href="#postgresql" title="Permalink to this headline">¶</a></h3>
<p>PostgreSQL is the most capable of all the databases here in terms of schema
support.</p>
<p>The only caveat is that prior to PostgreSQL 11, adding columns with default
values causes a full rewrite of the table, for a time proportional to its size.
For this reason, it’s recommended you always create new columns with
<code class="docutils literal notranslate"><span class="pre">null=True</span></code>, as this way they will be added immediately.</p>
</div>
<div class="section" id="s-mysql">
<span id="mysql"></span><h3>MySQL<a class="headerlink" href="#mysql" title="Permalink to this headline">¶</a></h3>
<p>MySQL lacks support for transactions around schema alteration operations,
meaning that if a migration fails to apply you will have to manually unpick
the changes in order to try again (it’s impossible to roll back to an
earlier point).</p>
<p>In addition, MySQL will fully rewrite tables for almost every schema operation
and generally takes a time proportional to the number of rows in the table to
add or remove columns. On slower hardware this can be worse than a minute per
million rows - adding a few columns to a table with just a few million rows
could lock your site up for over ten minutes.</p>
<p>Finally, MySQL has relatively small limits on name lengths for columns, tables
and indexes, as well as a limit on the combined size of all columns an index
covers. This means that indexes that are possible on other backends will
fail to be created under MySQL.</p>
</div>
<div class="section" id="s-sqlite">
<span id="sqlite"></span><h3>SQLite<a class="headerlink" href="#sqlite" title="Permalink to this headline">¶</a></h3>
<p>SQLite has very little built-in schema alteration support, and so Django
attempts to emulate it by:</p>
<ul class="simple">
<li>Creating a new table with the new schema</li>
<li>Copying the data across</li>
<li>Dropping the old table</li>
<li>Renaming the new table to match the original name</li>
</ul>
<p>This process generally works well, but it can be slow and occasionally
buggy. It is not recommended that you run and migrate SQLite in a
production environment unless you are very aware of the risks and
its limitations; the support Django ships with is designed to allow
developers to use SQLite on their local machines to develop less complex
Django projects without the need for a full database.</p>
</div>
</div>
<div class="section" id="s-workflow">
<span id="workflow"></span><h2>Workflow<a class="headerlink" href="#workflow" title="Permalink to this headline">¶</a></h2>
<p>Working with migrations is simple. Make changes to your models - say, add
a field and remove a model - and then run <a class="reference internal" href="../ref/django-admin.html#django-admin-makemigrations"><code class="xref std std-djadmin docutils literal notranslate"><span class="pre">makemigrations</span></code></a>:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span>$ python manage.py makemigrations
Migrations for &#39;books&#39;:
  books/migrations/0003_auto.py:
    - Alter field author on book
</pre></div>
</div>
<p>Your models will be scanned and compared to the versions currently
contained in your migration files, and then a new set of migrations
will be written out. Make sure to read the output to see what
<code class="docutils literal notranslate"><span class="pre">makemigrations</span></code> thinks you have changed - it’s not perfect, and for
complex changes it might not be detecting what you expect.</p>
<p>Once you have your new migration files, you should apply them to your
database to make sure they work as expected:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span>$ python manage.py migrate
Operations to perform:
  Apply all migrations: books
Running migrations:
  Rendering model states... DONE
  Applying books.0003_auto... OK
</pre></div>
</div>
<p>Once the migration is applied, commit the migration and the models change
to your version control system as a single commit - that way, when other
developers (or your production servers) check out the code, they’ll
get both the changes to your models and the accompanying migration at the
same time.</p>
<p>If you want to give the migration(s) a meaningful name instead of a generated
one, you can use the <a class="reference internal" href="../ref/django-admin.html#cmdoption-makemigrations-name"><code class="xref std std-option docutils literal notranslate"><span class="pre">makemigrations</span> <span class="pre">--name</span></code></a> option:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span>$ python manage.py makemigrations --name changed_my_model your_app_label
</pre></div>
</div>
<div class="section" id="s-version-control">
<span id="version-control"></span><h3>Version control<a class="headerlink" href="#version-control" title="Permalink to this headline">¶</a></h3>
<p>Because migrations are stored in version control, you’ll occasionally
come across situations where you and another developer have both committed
a migration to the same app at the same time, resulting in two migrations
with the same number.</p>
<p>Don’t worry - the numbers are just there for developers’ reference, Django
just cares that each migration has a different name. Migrations specify which
other migrations they depend on - including earlier migrations in the same
app - in the file, so it’s possible to detect when there’s two new migrations
for the same app that aren’t ordered.</p>
<p>When this happens, Django will prompt you and give you some options. If it
thinks it’s safe enough, it will offer to automatically linearize the two
migrations for you. If not, you’ll have to go in and modify the migrations
yourself - don’t worry, this isn’t difficult, and is explained more in
<a class="reference internal" href="#migration-files"><span class="std std-ref">Migration files</span></a> below.</p>
</div>
</div>
<div class="section" id="s-dependencies">
<span id="dependencies"></span><h2>Dependencies<a class="headerlink" href="#dependencies" title="Permalink to this headline">¶</a></h2>
<p>While migrations are per-app, the tables and relationships implied by
your models are too complex to be created for just one app at a time. When
you make a migration that requires something else to run - for example,
you add a <code class="docutils literal notranslate"><span class="pre">ForeignKey</span></code> in your <code class="docutils literal notranslate"><span class="pre">books</span></code> app to your <code class="docutils literal notranslate"><span class="pre">authors</span></code> app - the
resulting migration will contain a dependency on a migration in <code class="docutils literal notranslate"><span class="pre">authors</span></code>.</p>
<p>This means that when you run the migrations, the <code class="docutils literal notranslate"><span class="pre">authors</span></code> migration runs
first and creates the table the <code class="docutils literal notranslate"><span class="pre">ForeignKey</span></code> references, and then the migration
that makes the <code class="docutils literal notranslate"><span class="pre">ForeignKey</span></code> column runs afterwards and creates the constraint.
If this didn’t happen, the migration would try to create the <code class="docutils literal notranslate"><span class="pre">ForeignKey</span></code>
column without the table it’s referencing existing and your database would
throw an error.</p>
<p>This dependency behavior affects most migration operations where you
restrict to a single app. Restricting to a single app (either in
<code class="docutils literal notranslate"><span class="pre">makemigrations</span></code> or <code class="docutils literal notranslate"><span class="pre">migrate</span></code>) is a best-efforts promise, and not
a guarantee; any other apps that need to be used to get dependencies correct
will be.</p>
<p>Apps without migrations must not have relations (<code class="docutils literal notranslate"><span class="pre">ForeignKey</span></code>,
<code class="docutils literal notranslate"><span class="pre">ManyToManyField</span></code>, etc.) to apps with migrations. Sometimes it may work, but
it’s not supported.</p>
</div>
<div class="section" id="s-migration-files">
<span id="s-id1"></span><span id="migration-files"></span><span id="id1"></span><h2>Migration files<a class="headerlink" href="#migration-files" title="Permalink to this headline">¶</a></h2>
<p>Migrations are stored as an on-disk format, referred to here as
“migration files”. These files are actually just normal Python files with
an agreed-upon object layout, written in a declarative style.</p>
<p>A basic migration file looks like this:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">django.db</span> <span class="k">import</span> <span class="n">migrations</span><span class="p">,</span> <span class="n">models</span>

<span class="k">class</span> <span class="nc">Migration</span><span class="p">(</span><span class="n">migrations</span><span class="o">.</span><span class="n">Migration</span><span class="p">):</span>

    <span class="n">dependencies</span> <span class="o">=</span> <span class="p">[(</span><span class="s1">&#39;migrations&#39;</span><span class="p">,</span> <span class="s1">&#39;0001_initial&#39;</span><span class="p">)]</span>

    <span class="n">operations</span> <span class="o">=</span> <span class="p">[</span>
        <span class="n">migrations</span><span class="o">.</span><span class="n">DeleteModel</span><span class="p">(</span><span class="s1">&#39;Tribble&#39;</span><span class="p">),</span>
        <span class="n">migrations</span><span class="o">.</span><span class="n">AddField</span><span class="p">(</span><span class="s1">&#39;Author&#39;</span><span class="p">,</span> <span class="s1">&#39;rating&#39;</span><span class="p">,</span> <span class="n">models</span><span class="o">.</span><span class="n">IntegerField</span><span class="p">(</span><span class="n">default</span><span class="o">=</span><span class="mi">0</span><span class="p">)),</span>
    <span class="p">]</span>
</pre></div>
</div>
<p>What Django looks for when it loads a migration file (as a Python module) is
a subclass of <code class="docutils literal notranslate"><span class="pre">django.db.migrations.Migration</span></code> called <code class="docutils literal notranslate"><span class="pre">Migration</span></code>. It then
inspects this object for four attributes, only two of which are used
most of the time:</p>
<ul class="simple">
<li><code class="docutils literal notranslate"><span class="pre">dependencies</span></code>, a list of migrations this one depends on.</li>
<li><code class="docutils literal notranslate"><span class="pre">operations</span></code>, a list of <code class="docutils literal notranslate"><span class="pre">Operation</span></code> classes that define what this
migration does.</li>
</ul>
<p>The operations are the key; they are a set of declarative instructions which
tell Django what schema changes need to be made. Django scans them and
builds an in-memory representation of all of the schema changes to all apps,
and uses this to generate the SQL which makes the schema changes.</p>
<p>That in-memory structure is also used to work out what the differences are
between your models and the current state of your migrations; Django runs
through all the changes, in order, on an in-memory set of models to come
up with the state of your models last time you ran <code class="docutils literal notranslate"><span class="pre">makemigrations</span></code>. It
then uses these models to compare against the ones in your <code class="docutils literal notranslate"><span class="pre">models.py</span></code> files
to work out what you have changed.</p>
<p>You should rarely, if ever, need to edit migration files by hand, but
it’s entirely possible to write them manually if you need to. Some of the
more complex operations are not autodetectable and are only available via
a hand-written migration, so don’t be scared about editing them if you have to.</p>
<div class="section" id="s-custom-fields">
<span id="custom-fields"></span><h3>Custom fields<a class="headerlink" href="#custom-fields" title="Permalink to this headline">¶</a></h3>
<p>You can’t modify the number of positional arguments in an already migrated
custom field without raising a <code class="docutils literal notranslate"><span class="pre">TypeError</span></code>. The old migration will call the
modified <code class="docutils literal notranslate"><span class="pre">__init__</span></code> method with the old signature. So if you need a new
argument, please create a keyword argument and add something like
<code class="docutils literal notranslate"><span class="pre">assert</span> <span class="pre">'argument_name'</span> <span class="pre">in</span> <span class="pre">kwargs</span></code> in the constructor.</p>
</div>
<div class="section" id="s-model-managers">
<span id="s-using-managers-in-migrations"></span><span id="model-managers"></span><span id="using-managers-in-migrations"></span><h3>Model managers<a class="headerlink" href="#model-managers" title="Permalink to this headline">¶</a></h3>
<p>You can optionally serialize managers into migrations and have them available
in <a class="reference internal" href="../ref/migration-operations.html#django.db.migrations.operations.RunPython" title="django.db.migrations.operations.RunPython"><code class="xref py py-class docutils literal notranslate"><span class="pre">RunPython</span></code></a> operations. This is done
by defining a <code class="docutils literal notranslate"><span class="pre">use_in_migrations</span></code> attribute on the manager class:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">MyManager</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Manager</span><span class="p">):</span>
    <span class="n">use_in_migrations</span> <span class="o">=</span> <span class="kc">True</span>

<span class="k">class</span> <span class="nc">MyModel</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Model</span><span class="p">):</span>
    <span class="n">objects</span> <span class="o">=</span> <span class="n">MyManager</span><span class="p">()</span>
</pre></div>
</div>
<p>If you are using the <a class="reference internal" href="db/managers.html#django.db.models.from_queryset" title="django.db.models.from_queryset"><code class="xref py py-meth docutils literal notranslate"><span class="pre">from_queryset()</span></code></a> function to
dynamically generate a manager class, you need to inherit from the generated
class to make it importable:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">MyManager</span><span class="p">(</span><span class="n">MyBaseManager</span><span class="o">.</span><span class="n">from_queryset</span><span class="p">(</span><span class="n">CustomQuerySet</span><span class="p">)):</span>
    <span class="n">use_in_migrations</span> <span class="o">=</span> <span class="kc">True</span>

<span class="k">class</span> <span class="nc">MyModel</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Model</span><span class="p">):</span>
    <span class="n">objects</span> <span class="o">=</span> <span class="n">MyManager</span><span class="p">()</span>
</pre></div>
</div>
<p>Please refer to the notes about <a class="reference internal" href="#historical-models"><span class="std std-ref">Historical models</span></a> in migrations to see
the implications that come along.</p>
</div>
<div class="section" id="s-initial-migrations">
<span id="initial-migrations"></span><h3>Initial migrations<a class="headerlink" href="#initial-migrations" title="Permalink to this headline">¶</a></h3>
<dl class="attribute">
<dt id="django.db.migrations.Migration.initial">
<code class="descclassname">Migration.</code><code class="descname">initial</code><a class="headerlink" href="#django.db.migrations.Migration.initial" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>

<p>The “initial migrations” for an app are the migrations that create the first
version of that app’s tables. Usually an app will have just one initial
migration, but in some cases of complex model interdependencies it may have two
or more.</p>
<p>Initial migrations are marked with an <code class="docutils literal notranslate"><span class="pre">initial</span> <span class="pre">=</span> <span class="pre">True</span></code> class attribute on the
migration class. If an <code class="docutils literal notranslate"><span class="pre">initial</span></code> class attribute isn’t found, a migration
will be considered “initial” if it is the first migration in the app (i.e. if
it has no dependencies on any other migration in the same app).</p>
<p>When the <a class="reference internal" href="../ref/django-admin.html#cmdoption-migrate-fake-initial"><code class="xref std std-option docutils literal notranslate"><span class="pre">migrate</span> <span class="pre">--fake-initial</span></code></a> option is used, these initial
migrations are treated specially. For an initial migration that creates one or
more tables (<code class="docutils literal notranslate"><span class="pre">CreateModel</span></code> operation), Django checks that all of those tables
already exist in the database and fake-applies the migration if so. Similarly,
for an initial migration that adds one or more fields (<code class="docutils literal notranslate"><span class="pre">AddField</span></code> operation),
Django checks that all of the respective columns already exist in the database
and fake-applies the migration if so. Without <code class="docutils literal notranslate"><span class="pre">--fake-initial</span></code>, initial
migrations are treated no differently from any other migration.</p>
</div>
<div class="section" id="s-history-consistency">
<span id="s-migration-history-consistency"></span><span id="history-consistency"></span><span id="migration-history-consistency"></span><h3>History consistency<a class="headerlink" href="#history-consistency" title="Permalink to this headline">¶</a></h3>
<p>As previously discussed, you may need to linearize migrations manually when two
development branches are joined. While editing migration dependencies, you can
inadvertently create an inconsistent history state where a migration has been
applied but some of its dependencies haven’t. This is a strong indication that
the dependencies are incorrect, so Django will refuse to run migrations or make
new migrations until it’s fixed. When using multiple databases, you can use the
<a class="reference internal" href="db/multi-db.html#allow_migrate" title="allow_migrate"><code class="xref py py-meth docutils literal notranslate"><span class="pre">allow_migrate()</span></code></a> method of <a class="reference internal" href="db/multi-db.html#topics-db-multi-db-routing"><span class="std std-ref">database routers</span></a> to control which databases
<a class="reference internal" href="../ref/django-admin.html#django-admin-makemigrations"><code class="xref std std-djadmin docutils literal notranslate"><span class="pre">makemigrations</span></code></a> checks for consistent history.</p>
</div>
</div>
<div class="section" id="s-adding-migrations-to-apps">
<span id="adding-migrations-to-apps"></span><h2>Adding migrations to apps<a class="headerlink" href="#adding-migrations-to-apps" title="Permalink to this headline">¶</a></h2>
<p>Adding migrations to new apps is straightforward - they come preconfigured to
accept migrations, and so just run <a class="reference internal" href="../ref/django-admin.html#django-admin-makemigrations"><code class="xref std std-djadmin docutils literal notranslate"><span class="pre">makemigrations</span></code></a> once you’ve made
some changes.</p>
<p>If your app already has models and database tables, and doesn’t have migrations
yet (for example, you created it against a previous Django version), you’ll
need to convert it to use migrations; this is a simple process:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span>$ python manage.py makemigrations your_app_label
</pre></div>
</div>
<p>This will make a new initial migration for your app. Now, run <code class="docutils literal notranslate"><span class="pre">python</span>
<span class="pre">manage.py</span> <span class="pre">migrate</span> <span class="pre">--fake-initial</span></code>, and Django will detect that you have an
initial migration <em>and</em> that the tables it wants to create already exist, and
will mark the migration as already applied. (Without the <a class="reference internal" href="../ref/django-admin.html#cmdoption-migrate-fake-initial"><code class="xref std std-option docutils literal notranslate"><span class="pre">migrate</span>
<span class="pre">--fake-initial</span></code></a> flag, the command would error out because the tables it wants
to create already exist.)</p>
<p>Note that this only works given two things:</p>
<ul class="simple">
<li>You have not changed your models since you made their tables. For migrations
to work, you must make the initial migration <em>first</em> and then make changes,
as Django compares changes against migration files, not the database.</li>
<li>You have not manually edited your database - Django won’t be able to detect
that your database doesn’t match your models, you’ll just get errors when
migrations try to modify those tables.</li>
</ul>
</div>
<div class="section" id="s-reverting-migrations">
<span id="reverting-migrations"></span><h2>Reverting migrations<a class="headerlink" href="#reverting-migrations" title="Permalink to this headline">¶</a></h2>
<p>Any migration can be reverted with <a class="reference internal" href="../ref/django-admin.html#django-admin-migrate"><code class="xref std std-djadmin docutils literal notranslate"><span class="pre">migrate</span></code></a> by using the number of
previous migrations:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span>$ python manage.py migrate books 0002
Operations to perform:
  Target specific migration: 0002_auto, from books
Running migrations:
  Rendering model states... DONE
  Unapplying books.0003_auto... OK
</pre></div>
</div>
<p>If you want to revert all migrations applied for an app, use the name
<code class="docutils literal notranslate"><span class="pre">zero</span></code>:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span>$ python manage.py migrate books zero
Operations to perform:
  Unapply all migrations: books
Running migrations:
  Rendering model states... DONE
  Unapplying books.0002_auto... OK
  Unapplying books.0001_initial... OK
</pre></div>
</div>
</div>
<div class="section" id="s-historical-models">
<span id="s-id2"></span><span id="historical-models"></span><span id="id2"></span><h2>Historical models<a class="headerlink" href="#historical-models" title="Permalink to this headline">¶</a></h2>
<p>When you run migrations, Django is working from historical versions of your
models stored in the migration files. If you write Python code using the
<a class="reference internal" href="../ref/migration-operations.html#django.db.migrations.operations.RunPython" title="django.db.migrations.operations.RunPython"><code class="xref py py-class docutils literal notranslate"><span class="pre">RunPython</span></code></a> operation, or if you have
<code class="docutils literal notranslate"><span class="pre">allow_migrate</span></code> methods on your database routers, you <strong>need to use</strong> these
historical model versions rather than importing them directly.</p>
<div class="admonition warning">
<p class="first admonition-title">Warning</p>
<p>If you import models directly rather than using the historical models,
your migrations <em>may work initially</em> but will fail in the future when you
try to re-run old migrations (commonly, when you set up a new installation
and run through all the migrations to set up the database).</p>
<p class="last">This means that historical model problems may not be immediately obvious.
If you run into this kind of failure, it’s OK to edit the migration to use
the historical models rather than direct imports and commit those changes.</p>
</div>
<p>Because it’s impossible to serialize arbitrary Python code, these historical
models will not have any custom methods that you have defined. They will,
however, have the same fields, relationships, managers (limited to those with
<code class="docutils literal notranslate"><span class="pre">use_in_migrations</span> <span class="pre">=</span> <span class="pre">True</span></code>) and <code class="docutils literal notranslate"><span class="pre">Meta</span></code> options (also versioned, so they may
be different from your current ones).</p>
<div class="admonition warning">
<p class="first admonition-title">Warning</p>
<p class="last">This means that you will NOT have custom <code class="docutils literal notranslate"><span class="pre">save()</span></code> methods called on objects
when you access them in migrations, and you will NOT have any custom
constructors or instance methods. Plan appropriately!</p>
</div>
<p>References to functions in field options such as <code class="docutils literal notranslate"><span class="pre">upload_to</span></code> and
<code class="docutils literal notranslate"><span class="pre">limit_choices_to</span></code> and model manager declarations with managers having
<code class="docutils literal notranslate"><span class="pre">use_in_migrations</span> <span class="pre">=</span> <span class="pre">True</span></code> are serialized in migrations, so the functions and
classes will need to be kept around for as long as there is a migration
referencing them. Any <a class="reference internal" href="../howto/custom-model-fields.html"><span class="doc">custom model fields</span></a>
will also need to be kept, since these are imported directly by migrations.</p>
<p>In addition, the concrete base classes of the model are stored as pointers, so
you must always keep base classes around for as long as there is a migration
that contains a reference to them. On the plus side, methods and managers from
these base classes inherit normally, so if you absolutely need access to these
you can opt to move them into a superclass.</p>
<p>To remove old references, you can <a class="reference internal" href="#migration-squashing"><span class="std std-ref">squash migrations</span></a>
or, if there aren’t many references, copy them into the migration files.</p>
</div>
<div class="section" id="s-considerations-when-removing-model-fields">
<span id="s-migrations-removing-model-fields"></span><span id="considerations-when-removing-model-fields"></span><span id="migrations-removing-model-fields"></span><h2>Considerations when removing model fields<a class="headerlink" href="#considerations-when-removing-model-fields" title="Permalink to this headline">¶</a></h2>
<p>Similar to the “references to historical functions” considerations described in
the previous section, removing custom model fields from your project or
third-party app will cause a problem if they are referenced in old migrations.</p>
<p>To help with this situation, Django provides some model field attributes to
assist with model field deprecation using the <a class="reference internal" href="checks.html"><span class="doc">system checks framework</span></a>.</p>
<p>Add the <code class="docutils literal notranslate"><span class="pre">system_check_deprecated_details</span></code> attribute to your model field
similar to the following:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">IPAddressField</span><span class="p">(</span><span class="n">Field</span><span class="p">):</span>
    <span class="n">system_check_deprecated_details</span> <span class="o">=</span> <span class="p">{</span>
        <span class="s1">&#39;msg&#39;</span><span class="p">:</span> <span class="p">(</span>
            <span class="s1">&#39;IPAddressField has been deprecated. Support for it (except &#39;</span>
            <span class="s1">&#39;in historical migrations) will be removed in Django 1.9.&#39;</span>
        <span class="p">),</span>
        <span class="s1">&#39;hint&#39;</span><span class="p">:</span> <span class="s1">&#39;Use GenericIPAddressField instead.&#39;</span><span class="p">,</span>  <span class="c1"># optional</span>
        <span class="s1">&#39;id&#39;</span><span class="p">:</span> <span class="s1">&#39;fields.W900&#39;</span><span class="p">,</span>  <span class="c1"># pick a unique ID for your field.</span>
    <span class="p">}</span>
</pre></div>
</div>
<p>After a deprecation period of your choosing (two or three feature releases for
fields in Django itself), change the <code class="docutils literal notranslate"><span class="pre">system_check_deprecated_details</span></code>
attribute to <code class="docutils literal notranslate"><span class="pre">system_check_removed_details</span></code> and update the dictionary similar
to:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">IPAddressField</span><span class="p">(</span><span class="n">Field</span><span class="p">):</span>
    <span class="n">system_check_removed_details</span> <span class="o">=</span> <span class="p">{</span>
        <span class="s1">&#39;msg&#39;</span><span class="p">:</span> <span class="p">(</span>
            <span class="s1">&#39;IPAddressField has been removed except for support in &#39;</span>
            <span class="s1">&#39;historical migrations.&#39;</span>
        <span class="p">),</span>
        <span class="s1">&#39;hint&#39;</span><span class="p">:</span> <span class="s1">&#39;Use GenericIPAddressField instead.&#39;</span><span class="p">,</span>
        <span class="s1">&#39;id&#39;</span><span class="p">:</span> <span class="s1">&#39;fields.E900&#39;</span><span class="p">,</span>  <span class="c1"># pick a unique ID for your field.</span>
    <span class="p">}</span>
</pre></div>
</div>
<p>You should keep the field’s methods that are required for it to operate in
database migrations such as <code class="docutils literal notranslate"><span class="pre">__init__()</span></code>, <code class="docutils literal notranslate"><span class="pre">deconstruct()</span></code>, and
<code class="docutils literal notranslate"><span class="pre">get_internal_type()</span></code>. Keep this stub field for as long as any migrations
which reference the field exist. For example, after squashing migrations and
removing the old ones, you should be able to remove the field completely.</p>
</div>
<div class="section" id="s-data-migrations">
<span id="s-id3"></span><span id="data-migrations"></span><span id="id3"></span><h2>Data Migrations<a class="headerlink" href="#data-migrations" title="Permalink to this headline">¶</a></h2>
<p>As well as changing the database schema, you can also use migrations to change
the data in the database itself, in conjunction with the schema if you want.</p>
<p>Migrations that alter data are usually called “data migrations”; they’re best
written as separate migrations, sitting alongside your schema migrations.</p>
<p>Django can’t automatically generate data migrations for you, as it does with
schema migrations, but it’s not very hard to write them. Migration files in
Django are made up of <a class="reference internal" href="../ref/migration-operations.html"><span class="doc">Operations</span></a>, and
the main operation you use for data migrations is
<a class="reference internal" href="../ref/migration-operations.html#django.db.migrations.operations.RunPython" title="django.db.migrations.operations.RunPython"><code class="xref py py-class docutils literal notranslate"><span class="pre">RunPython</span></code></a>.</p>
<p>To start, make an empty migration file you can work from (Django will put
the file in the right place, suggest a name, and add dependencies for you):</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">python</span> <span class="n">manage</span><span class="o">.</span><span class="n">py</span> <span class="n">makemigrations</span> <span class="o">--</span><span class="n">empty</span> <span class="n">yourappname</span>
</pre></div>
</div>
<p>Then, open up the file; it should look something like this:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="c1"># Generated by Django A.B on YYYY-MM-DD HH:MM</span>
<span class="kn">from</span> <span class="nn">django.db</span> <span class="k">import</span> <span class="n">migrations</span>

<span class="k">class</span> <span class="nc">Migration</span><span class="p">(</span><span class="n">migrations</span><span class="o">.</span><span class="n">Migration</span><span class="p">):</span>

    <span class="n">dependencies</span> <span class="o">=</span> <span class="p">[</span>
        <span class="p">(</span><span class="s1">&#39;yourappname&#39;</span><span class="p">,</span> <span class="s1">&#39;0001_initial&#39;</span><span class="p">),</span>
    <span class="p">]</span>

    <span class="n">operations</span> <span class="o">=</span> <span class="p">[</span>
    <span class="p">]</span>
</pre></div>
</div>
<p>Now, all you need to do is create a new function and have
<a class="reference internal" href="../ref/migration-operations.html#django.db.migrations.operations.RunPython" title="django.db.migrations.operations.RunPython"><code class="xref py py-class docutils literal notranslate"><span class="pre">RunPython</span></code></a> use it.
<a class="reference internal" href="../ref/migration-operations.html#django.db.migrations.operations.RunPython" title="django.db.migrations.operations.RunPython"><code class="xref py py-class docutils literal notranslate"><span class="pre">RunPython</span></code></a> expects a callable as its argument
which takes two arguments - the first is an <a class="reference internal" href="../ref/applications.html"><span class="doc">app registry</span></a> that has the historical versions of all your models
loaded into it to match where in your history the migration sits, and the
second is a <a class="reference internal" href="../ref/schema-editor.html"><span class="doc">SchemaEditor</span></a>, which you can use to
manually effect database schema changes (but beware, doing this can confuse
the migration autodetector!)</p>
<p>Let’s write a simple migration that populates our new <code class="docutils literal notranslate"><span class="pre">name</span></code> field with the
combined values of <code class="docutils literal notranslate"><span class="pre">first_name</span></code> and <code class="docutils literal notranslate"><span class="pre">last_name</span></code> (we’ve come to our senses
and realized that not everyone has first and last names). All we
need to do is use the historical model and iterate over the rows:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">django.db</span> <span class="k">import</span> <span class="n">migrations</span>

<span class="k">def</span> <span class="nf">combine_names</span><span class="p">(</span><span class="n">apps</span><span class="p">,</span> <span class="n">schema_editor</span><span class="p">):</span>
    <span class="c1"># We can&#39;t import the Person model directly as it may be a newer</span>
    <span class="c1"># version than this migration expects. We use the historical version.</span>
    <span class="n">Person</span> <span class="o">=</span> <span class="n">apps</span><span class="o">.</span><span class="n">get_model</span><span class="p">(</span><span class="s1">&#39;yourappname&#39;</span><span class="p">,</span> <span class="s1">&#39;Person&#39;</span><span class="p">)</span>
    <span class="k">for</span> <span class="n">person</span> <span class="ow">in</span> <span class="n">Person</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">all</span><span class="p">():</span>
        <span class="n">person</span><span class="o">.</span><span class="n">name</span> <span class="o">=</span> <span class="s1">&#39;</span><span class="si">%s</span><span class="s1"> </span><span class="si">%s</span><span class="s1">&#39;</span> <span class="o">%</span> <span class="p">(</span><span class="n">person</span><span class="o">.</span><span class="n">first_name</span><span class="p">,</span> <span class="n">person</span><span class="o">.</span><span class="n">last_name</span><span class="p">)</span>
        <span class="n">person</span><span class="o">.</span><span class="n">save</span><span class="p">()</span>

<span class="k">class</span> <span class="nc">Migration</span><span class="p">(</span><span class="n">migrations</span><span class="o">.</span><span class="n">Migration</span><span class="p">):</span>

    <span class="n">dependencies</span> <span class="o">=</span> <span class="p">[</span>
        <span class="p">(</span><span class="s1">&#39;yourappname&#39;</span><span class="p">,</span> <span class="s1">&#39;0001_initial&#39;</span><span class="p">),</span>
    <span class="p">]</span>

    <span class="n">operations</span> <span class="o">=</span> <span class="p">[</span>
        <span class="n">migrations</span><span class="o">.</span><span class="n">RunPython</span><span class="p">(</span><span class="n">combine_names</span><span class="p">),</span>
    <span class="p">]</span>
</pre></div>
</div>
<p>Once that’s done, we can just run <code class="docutils literal notranslate"><span class="pre">python</span> <span class="pre">manage.py</span> <span class="pre">migrate</span></code> as normal and
the data migration will run in place alongside other migrations.</p>
<p>You can pass a second callable to
<a class="reference internal" href="../ref/migration-operations.html#django.db.migrations.operations.RunPython" title="django.db.migrations.operations.RunPython"><code class="xref py py-class docutils literal notranslate"><span class="pre">RunPython</span></code></a> to run whatever logic you
want executed when migrating backwards. If this callable is omitted, migrating
backwards will raise an exception.</p>
<div class="section" id="s-accessing-models-from-other-apps">
<span id="accessing-models-from-other-apps"></span><h3>Accessing models from other apps<a class="headerlink" href="#accessing-models-from-other-apps" title="Permalink to this headline">¶</a></h3>
<p>When writing a <code class="docutils literal notranslate"><span class="pre">RunPython</span></code> function that uses models from apps other than the
one in which the migration is located, the migration’s <code class="docutils literal notranslate"><span class="pre">dependencies</span></code>
attribute should include the latest migration of each app that is involved,
otherwise you may get an error similar to: <code class="docutils literal notranslate"><span class="pre">LookupError:</span> <span class="pre">No</span> <span class="pre">installed</span> <span class="pre">app</span>
<span class="pre">with</span> <span class="pre">label</span> <span class="pre">'myappname'</span></code> when you try to retrieve the model in the <code class="docutils literal notranslate"><span class="pre">RunPython</span></code>
function using <code class="docutils literal notranslate"><span class="pre">apps.get_model()</span></code>.</p>
<p>In the following example, we have a migration in <code class="docutils literal notranslate"><span class="pre">app1</span></code> which needs to use
models in <code class="docutils literal notranslate"><span class="pre">app2</span></code>. We aren’t concerned with the details of <code class="docutils literal notranslate"><span class="pre">move_m1</span></code> other
than the fact it will need to access models from both apps. Therefore we’ve
added a dependency that specifies the last migration of <code class="docutils literal notranslate"><span class="pre">app2</span></code>:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">Migration</span><span class="p">(</span><span class="n">migrations</span><span class="o">.</span><span class="n">Migration</span><span class="p">):</span>

    <span class="n">dependencies</span> <span class="o">=</span> <span class="p">[</span>
        <span class="p">(</span><span class="s1">&#39;app1&#39;</span><span class="p">,</span> <span class="s1">&#39;0001_initial&#39;</span><span class="p">),</span>
        <span class="c1"># added dependency to enable using models from app2 in move_m1</span>
        <span class="p">(</span><span class="s1">&#39;app2&#39;</span><span class="p">,</span> <span class="s1">&#39;0004_foobar&#39;</span><span class="p">),</span>
    <span class="p">]</span>

    <span class="n">operations</span> <span class="o">=</span> <span class="p">[</span>
        <span class="n">migrations</span><span class="o">.</span><span class="n">RunPython</span><span class="p">(</span><span class="n">move_m1</span><span class="p">),</span>
    <span class="p">]</span>
</pre></div>
</div>
</div>
<div class="section" id="s-more-advanced-migrations">
<span id="more-advanced-migrations"></span><h3>More advanced migrations<a class="headerlink" href="#more-advanced-migrations" title="Permalink to this headline">¶</a></h3>
<p>If you’re interested in the more advanced migration operations, or want
to be able to write your own, see the <a class="reference internal" href="../ref/migration-operations.html"><span class="doc">migration operations reference</span></a> and the “how-to” on <a class="reference internal" href="../howto/writing-migrations.html"><span class="doc">writing migrations</span></a>.</p>
</div>
</div>
<div class="section" id="s-squashing-migrations">
<span id="s-migration-squashing"></span><span id="squashing-migrations"></span><span id="migration-squashing"></span><h2>Squashing migrations<a class="headerlink" href="#squashing-migrations" title="Permalink to this headline">¶</a></h2>
<p>You are encouraged to make migrations freely and not worry about how many you
have; the migration code is optimized to deal with hundreds at a time without
much slowdown. However, eventually you will want to move back from having
several hundred migrations to just a few, and that’s where squashing comes in.</p>
<p>Squashing is the act of reducing an existing set of many migrations down to
one (or sometimes a few) migrations which still represent the same changes.</p>
<p>Django does this by taking all of your existing migrations, extracting their
<code class="docutils literal notranslate"><span class="pre">Operation</span></code>s and putting them all in sequence, and then running an optimizer
over them to try and reduce the length of the list - for example, it knows
that <a class="reference internal" href="../ref/migration-operations.html#django.db.migrations.operations.CreateModel" title="django.db.migrations.operations.CreateModel"><code class="xref py py-class docutils literal notranslate"><span class="pre">CreateModel</span></code></a> and
<a class="reference internal" href="../ref/migration-operations.html#django.db.migrations.operations.DeleteModel" title="django.db.migrations.operations.DeleteModel"><code class="xref py py-class docutils literal notranslate"><span class="pre">DeleteModel</span></code></a> cancel each other out,
and it knows that <a class="reference internal" href="../ref/migration-operations.html#django.db.migrations.operations.AddField" title="django.db.migrations.operations.AddField"><code class="xref py py-class docutils literal notranslate"><span class="pre">AddField</span></code></a> can be
rolled into <a class="reference internal" href="../ref/migration-operations.html#django.db.migrations.operations.CreateModel" title="django.db.migrations.operations.CreateModel"><code class="xref py py-class docutils literal notranslate"><span class="pre">CreateModel</span></code></a>.</p>
<p>Once the operation sequence has been reduced as much as possible - the amount
possible depends on how closely intertwined your models are and if you have
any <a class="reference internal" href="../ref/migration-operations.html#django.db.migrations.operations.RunSQL" title="django.db.migrations.operations.RunSQL"><code class="xref py py-class docutils literal notranslate"><span class="pre">RunSQL</span></code></a>
or <a class="reference internal" href="../ref/migration-operations.html#django.db.migrations.operations.RunPython" title="django.db.migrations.operations.RunPython"><code class="xref py py-class docutils literal notranslate"><span class="pre">RunPython</span></code></a> operations (which can’t
be optimized through unless they are marked as <code class="docutils literal notranslate"><span class="pre">elidable</span></code>) - Django will then
write it back out into a new set of migration files.</p>
<p>These files are marked to say they replace the previously-squashed migrations,
so they can coexist with the old migration files, and Django will intelligently
switch between them depending where you are in the history. If you’re still
part-way through the set of migrations that you squashed, it will keep using
them until it hits the end and then switch to the squashed history, while new
installs will just use the new squashed migration and skip all the old ones.</p>
<p>This enables you to squash and not mess up systems currently in production
that aren’t fully up-to-date yet. The recommended process is to squash, keeping
the old files, commit and release, wait until all systems are upgraded with
the new release (or if you’re a third-party project, just ensure your users
upgrade releases in order without skipping any), and then remove the old files,
commit and do a second release.</p>
<p>The command that backs all this is <a class="reference internal" href="../ref/django-admin.html#django-admin-squashmigrations"><code class="xref std std-djadmin docutils literal notranslate"><span class="pre">squashmigrations</span></code></a> - just pass
it the app label and migration name you want to squash up to, and it’ll get to
work:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span>$ ./manage.py squashmigrations myapp 0004
Will squash the following migrations:
 - 0001_initial
 - 0002_some_change
 - 0003_another_change
 - 0004_undo_something
Do you wish to proceed? [yN] y
Optimizing...
  Optimized from 12 operations to 7 operations.
Created new squashed migration /home/andrew/Programs/DjangoTest/test/migrations/0001_squashed_0004_undo_somthing.py
  You should commit this migration but leave the old ones in place;
  the new migration will be used for new installs. Once you are sure
  all instances of the codebase have applied the migrations you squashed,
  you can delete them.
</pre></div>
</div>
<p>Use the <a class="reference internal" href="../ref/django-admin.html#cmdoption-squashmigrations-squashed-name"><code class="xref std std-option docutils literal notranslate"><span class="pre">squashmigrations</span> <span class="pre">--squashed-name</span></code></a> option if you want to set
the name of the squashed migration rather than use an autogenerated one.</p>
<p>Note that model interdependencies in Django can get very complex, and squashing
may result in migrations that do not run; either mis-optimized (in which case
you can try again with <code class="docutils literal notranslate"><span class="pre">--no-optimize</span></code>, though you should also report an issue),
or with a <code class="docutils literal notranslate"><span class="pre">CircularDependencyError</span></code>, in which case you can manually resolve it.</p>
<p>To manually resolve a <code class="docutils literal notranslate"><span class="pre">CircularDependencyError</span></code>, break out one of
the ForeignKeys in the circular dependency loop into a separate
migration, and move the dependency on the other app with it. If you’re unsure,
see how <a class="reference internal" href="../ref/django-admin.html#django-admin-makemigrations"><code class="xref std std-djadmin docutils literal notranslate"><span class="pre">makemigrations</span></code></a> deals with the problem when asked to create
brand new migrations from your models. In a future release of Django,
<a class="reference internal" href="../ref/django-admin.html#django-admin-squashmigrations"><code class="xref std std-djadmin docutils literal notranslate"><span class="pre">squashmigrations</span></code></a> will be updated to attempt to resolve these errors
itself.</p>
<p>Once you’ve squashed your migration, you should then commit it alongside the
migrations it replaces and distribute this change to all running instances
of your application, making sure that they run <code class="docutils literal notranslate"><span class="pre">migrate</span></code> to store the change
in their database.</p>
<p>You must then transition the squashed migration to a normal migration by:</p>
<ul class="simple">
<li>Deleting all the migration files it replaces.</li>
<li>Updating all migrations that depend on the deleted migrations to depend on
the squashed migration instead.</li>
<li>Removing the <code class="docutils literal notranslate"><span class="pre">replaces</span></code> attribute in the <code class="docutils literal notranslate"><span class="pre">Migration</span></code> class of the
squashed migration (this is how Django tells that it is a squashed migration).</li>
</ul>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">Once you’ve squashed a migration, you should not then re-squash that squashed
migration until you have fully transitioned it to a normal migration.</p>
</div>
</div>
<div class="section" id="s-serializing-values">
<span id="s-migration-serializing"></span><span id="serializing-values"></span><span id="migration-serializing"></span><h2>Serializing values<a class="headerlink" href="#serializing-values" title="Permalink to this headline">¶</a></h2>
<p>Migrations are just Python files containing the old definitions of your models
- thus, to write them, Django must take the current state of your models and
serialize them out into a file.</p>
<p>While Django can serialize most things, there are some things that we just
can’t serialize out into a valid Python representation - there’s no Python
standard for how a value can be turned back into code (<code class="docutils literal notranslate"><span class="pre">repr()</span></code> only works
for basic values, and doesn’t specify import paths).</p>
<p>Django can serialize the following:</p>
<ul class="simple">
<li><code class="docutils literal notranslate"><span class="pre">int</span></code>, <code class="docutils literal notranslate"><span class="pre">float</span></code>, <code class="docutils literal notranslate"><span class="pre">bool</span></code>, <code class="docutils literal notranslate"><span class="pre">str</span></code>, <code class="docutils literal notranslate"><span class="pre">bytes</span></code>, <code class="docutils literal notranslate"><span class="pre">None</span></code>, <code class="docutils literal notranslate"><span class="pre">NoneType</span></code></li>
<li><code class="docutils literal notranslate"><span class="pre">list</span></code>, <code class="docutils literal notranslate"><span class="pre">set</span></code>, <code class="docutils literal notranslate"><span class="pre">tuple</span></code>, <code class="docutils literal notranslate"><span class="pre">dict</span></code>, <code class="docutils literal notranslate"><span class="pre">range</span></code>.</li>
<li><code class="docutils literal notranslate"><span class="pre">datetime.date</span></code>, <code class="docutils literal notranslate"><span class="pre">datetime.time</span></code>, and <code class="docutils literal notranslate"><span class="pre">datetime.datetime</span></code> instances
(include those that are timezone-aware)</li>
<li><code class="docutils literal notranslate"><span class="pre">decimal.Decimal</span></code> instances</li>
<li><code class="docutils literal notranslate"><span class="pre">enum.Enum</span></code> instances</li>
<li><code class="docutils literal notranslate"><span class="pre">uuid.UUID</span></code> instances</li>
<li><a class="reference external" href="https://docs.python.org/3/library/functools.html#functools.partial" title="(in Python v3.8)"><code class="xref py py-func docutils literal notranslate"><span class="pre">functools.partial()</span></code></a> and <a class="reference external" href="https://docs.python.org/3/library/functools.html#functools.partialmethod" title="(in Python v3.8)"><code class="xref py py-class docutils literal notranslate"><span class="pre">functools.partialmethod</span></code></a> instances
which have serializable <code class="docutils literal notranslate"><span class="pre">func</span></code>, <code class="docutils literal notranslate"><span class="pre">args</span></code>, and <code class="docutils literal notranslate"><span class="pre">keywords</span></code> values.</li>
<li><code class="docutils literal notranslate"><span class="pre">LazyObject</span></code> instances which wrap a serializable value.</li>
<li>Any Django field</li>
<li>Any function or method reference (e.g. <code class="docutils literal notranslate"><span class="pre">datetime.datetime.today</span></code>) (must be in module’s top-level scope)</li>
<li>Unbound methods used from within the class body</li>
<li>Any class reference (must be in module’s top-level scope)</li>
<li>Anything with a custom <code class="docutils literal notranslate"><span class="pre">deconstruct()</span></code> method (<a class="reference internal" href="#custom-deconstruct-method"><span class="std std-ref">see below</span></a>)</li>
</ul>
<div class="versionchanged">
<span class="title">Changed in Django 2.1:</span> <p>Serialization support for <a class="reference external" href="https://docs.python.org/3/library/functools.html#functools.partialmethod" title="(in Python v3.8)"><code class="xref py py-class docutils literal notranslate"><span class="pre">functools.partialmethod</span></code></a> was added.</p>
</div>
<div class="versionchanged">
<span class="title">Changed in Django 2.2:</span> <p>Serialization support for <code class="docutils literal notranslate"><span class="pre">NoneType</span></code> was added.</p>
</div>
<p>Django cannot serialize:</p>
<ul class="simple">
<li>Nested classes</li>
<li>Arbitrary class instances (e.g. <code class="docutils literal notranslate"><span class="pre">MyClass(4.3,</span> <span class="pre">5.7)</span></code>)</li>
<li>Lambdas</li>
</ul>
<div class="section" id="s-custom-serializers">
<span id="s-custom-migration-serializers"></span><span id="custom-serializers"></span><span id="custom-migration-serializers"></span><h3>Custom serializers<a class="headerlink" href="#custom-serializers" title="Permalink to this headline">¶</a></h3>
<div class="versionadded">
<span class="title">New in Django 2.2.</span> </div>
<p>You can serialize other types by writing a custom serializer. For example, if
Django didn’t serialize <a class="reference external" href="https://docs.python.org/3/library/decimal.html#decimal.Decimal" title="(in Python v3.8)"><code class="xref py py-class docutils literal notranslate"><span class="pre">Decimal</span></code></a> by default, you could do
this:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">decimal</span> <span class="k">import</span> <span class="n">Decimal</span>

<span class="kn">from</span> <span class="nn">django.db.migrations.serializer</span> <span class="k">import</span> <span class="n">BaseSerializer</span>
<span class="kn">from</span> <span class="nn">django.db.migrations.writer</span> <span class="k">import</span> <span class="n">MigrationWriter</span>

<span class="k">class</span> <span class="nc">DecimalSerializer</span><span class="p">(</span><span class="n">BaseSerializer</span><span class="p">):</span>
    <span class="k">def</span> <span class="nf">serialize</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="k">return</span> <span class="nb">repr</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">value</span><span class="p">),</span> <span class="p">{</span><span class="s1">&#39;from decimal import Decimal&#39;</span><span class="p">}</span>

<span class="n">MigrationWriter</span><span class="o">.</span><span class="n">register_serializer</span><span class="p">(</span><span class="n">Decimal</span><span class="p">,</span> <span class="n">DecimalSerializer</span><span class="p">)</span>
</pre></div>
</div>
<p>The first argument of <code class="docutils literal notranslate"><span class="pre">MigrationWriter.register_serializer()</span></code> is a type or
iterable of types that should use the serializer.</p>
<p>The <code class="docutils literal notranslate"><span class="pre">serialize()</span></code> method of your serializer must return a string of how the
value should appear in migrations and a set of any imports that are needed in
the migration.</p>
</div>
<div class="section" id="s-adding-a-deconstruct-method">
<span id="s-custom-deconstruct-method"></span><span id="adding-a-deconstruct-method"></span><span id="custom-deconstruct-method"></span><h3>Adding a <code class="docutils literal notranslate"><span class="pre">deconstruct()</span></code> method<a class="headerlink" href="#adding-a-deconstruct-method" title="Permalink to this headline">¶</a></h3>
<p>You can let Django serialize your own custom class instances by giving the class
a <code class="docutils literal notranslate"><span class="pre">deconstruct()</span></code> method. It takes no arguments, and should return a tuple
of three things <code class="docutils literal notranslate"><span class="pre">(path,</span> <span class="pre">args,</span> <span class="pre">kwargs)</span></code>:</p>
<ul class="simple">
<li><code class="docutils literal notranslate"><span class="pre">path</span></code> should be the Python path to the class, with the class name included
as the last part (for example, <code class="docutils literal notranslate"><span class="pre">myapp.custom_things.MyClass</span></code>). If your
class is not available at the top level of a module it is not serializable.</li>
<li><code class="docutils literal notranslate"><span class="pre">args</span></code> should be a list of positional arguments to pass to your class’
<code class="docutils literal notranslate"><span class="pre">__init__</span></code> method. Everything in this list should itself be serializable.</li>
<li><code class="docutils literal notranslate"><span class="pre">kwargs</span></code> should be a dict of keyword arguments to pass to your class’
<code class="docutils literal notranslate"><span class="pre">__init__</span></code> method. Every value should itself be serializable.</li>
</ul>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">This return value is different from the <code class="docutils literal notranslate"><span class="pre">deconstruct()</span></code> method
<a class="reference internal" href="../howto/custom-model-fields.html#custom-field-deconstruct-method"><span class="std std-ref">for custom fields</span></a> which returns a
tuple of four items.</p>
</div>
<p>Django will write out the value as an instantiation of your class with the
given arguments, similar to the way it writes out references to Django fields.</p>
<p>To prevent a new migration from being created each time
<a class="reference internal" href="../ref/django-admin.html#django-admin-makemigrations"><code class="xref std std-djadmin docutils literal notranslate"><span class="pre">makemigrations</span></code></a> is run, you should also add a <code class="docutils literal notranslate"><span class="pre">__eq__()</span></code> method to
the decorated class. This function will be called by Django’s migration
framework to detect changes between states.</p>
<p>As long as all of the arguments to your class’ constructor are themselves
serializable, you can use the <code class="docutils literal notranslate"><span class="pre">&#64;deconstructible</span></code> class decorator from
<code class="docutils literal notranslate"><span class="pre">django.utils.deconstruct</span></code> to add the <code class="docutils literal notranslate"><span class="pre">deconstruct()</span></code> method:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">django.utils.deconstruct</span> <span class="k">import</span> <span class="n">deconstructible</span>

<span class="nd">@deconstructible</span>
<span class="k">class</span> <span class="nc">MyCustomClass</span><span class="p">:</span>

    <span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">foo</span><span class="o">=</span><span class="mi">1</span><span class="p">):</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">foo</span> <span class="o">=</span> <span class="n">foo</span>
        <span class="o">...</span>

    <span class="k">def</span> <span class="nf">__eq__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">other</span><span class="p">):</span>
        <span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">foo</span> <span class="o">==</span> <span class="n">other</span><span class="o">.</span><span class="n">foo</span>
</pre></div>
</div>
<p>The decorator adds logic to capture and preserve the arguments on their
way into your constructor, and then returns those arguments exactly when
deconstruct() is called.</p>
</div>
</div>
<div class="section" id="s-supporting-multiple-django-versions">
<span id="supporting-multiple-django-versions"></span><h2>Supporting multiple Django versions<a class="headerlink" href="#supporting-multiple-django-versions" title="Permalink to this headline">¶</a></h2>
<p>If you are the maintainer of a third-party app with models, you may need to
ship migrations that support multiple Django versions. In this case, you should
always run <a class="reference internal" href="../ref/django-admin.html#django-admin-makemigrations"><code class="xref std std-djadmin docutils literal notranslate"><span class="pre">makemigrations</span></code></a> <strong>with the lowest Django version you wish
to support</strong>.</p>
<p>The migrations system will maintain backwards-compatibility according to the
same policy as the rest of Django, so migration files generated on Django X.Y
should run unchanged on Django X.Y+1. The migrations system does not promise
forwards-compatibility, however. New features may be added, and migration files
generated with newer versions of Django may not work on older versions.</p>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt><a class="reference internal" href="../ref/migration-operations.html"><span class="doc">The Migrations Operations Reference</span></a></dt>
<dd>Covers the schema operations API, special operations, and writing your
own operations.</dd>
<dt><a class="reference internal" href="../howto/writing-migrations.html"><span class="doc">The Writing Migrations “how-to”</span></a></dt>
<dd>Explains how to structure and write database migrations for different
scenarios you might encounter.</dd>
</dl>
</div>
</div>
</div>


          </div>
        </div>
      </div>
      
        
          <div class="yui-b" id="sidebar">
            
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">Migrations</a><ul>
<li><a class="reference internal" href="#the-commands">The Commands</a></li>
<li><a class="reference internal" href="#backend-support">Backend Support</a><ul>
<li><a class="reference internal" href="#postgresql">PostgreSQL</a></li>
<li><a class="reference internal" href="#mysql">MySQL</a></li>
<li><a class="reference internal" href="#sqlite">SQLite</a></li>
</ul>
</li>
<li><a class="reference internal" href="#workflow">Workflow</a><ul>
<li><a class="reference internal" href="#version-control">Version control</a></li>
</ul>
</li>
<li><a class="reference internal" href="#dependencies">Dependencies</a></li>
<li><a class="reference internal" href="#migration-files">Migration files</a><ul>
<li><a class="reference internal" href="#custom-fields">Custom fields</a></li>
<li><a class="reference internal" href="#model-managers">Model managers</a></li>
<li><a class="reference internal" href="#initial-migrations">Initial migrations</a></li>
<li><a class="reference internal" href="#history-consistency">History consistency</a></li>
</ul>
</li>
<li><a class="reference internal" href="#adding-migrations-to-apps">Adding migrations to apps</a></li>
<li><a class="reference internal" href="#reverting-migrations">Reverting migrations</a></li>
<li><a class="reference internal" href="#historical-models">Historical models</a></li>
<li><a class="reference internal" href="#considerations-when-removing-model-fields">Considerations when removing model fields</a></li>
<li><a class="reference internal" href="#data-migrations">Data Migrations</a><ul>
<li><a class="reference internal" href="#accessing-models-from-other-apps">Accessing models from other apps</a></li>
<li><a class="reference internal" href="#more-advanced-migrations">More advanced migrations</a></li>
</ul>
</li>
<li><a class="reference internal" href="#squashing-migrations">Squashing migrations</a></li>
<li><a class="reference internal" href="#serializing-values">Serializing values</a><ul>
<li><a class="reference internal" href="#custom-serializers">Custom serializers</a></li>
<li><a class="reference internal" href="#adding-a-deconstruct-method">Adding a <code class="docutils literal notranslate"><span class="pre">deconstruct()</span></code> method</a></li>
</ul>
</li>
<li><a class="reference internal" href="#supporting-multiple-django-versions">Supporting multiple Django versions</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="class-based-views/mixins.html"
                        title="previous chapter">Using mixins with class-based views</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="files.html"
                        title="next chapter">Managing files</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/topics/migrations.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
              <h3>Last update:</h3>
              <p class="topless">Mar 04, 2020</p>
          </div>
        
      
    </div>

    <div id="ft">
      <div class="nav">
    &laquo; <a href="class-based-views/mixins.html" title="Using mixins with class-based views">previous</a>
     |
    <a href="index.html" title="Using Django" accesskey="U">up</a>
   |
    <a href="files.html" title="Managing files">next</a> &raquo;</div>
    </div>
  </div>

      <div class="clearer"></div>
    </div>
  </body>
</html>